package com.kc.demo.kcapidemo.mqtt;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

@Component
public class MqttRunServer implements InitializingBean {


    public static MqttClient mqttClient = null;
    public static MemoryPersistence persistence = new MemoryPersistence();
    public static String pubTopic = "kc_wr";
    public static String broker = "tcp://127.0.0.1:1883";
    public static String clientId = "emqx_test";
    public static int qos = 2;

    public void init() throws MqttException {
        mqttClient = new MqttClient(broker, clientId, persistence);
        // MQTT 连接选项
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setUserName("kcadmin");
        connOpts.setPassword("12345678".toCharArray());
        // 保留会话
        connOpts.setCleanSession(true);
        mqttClient.connect(connOpts);

    }

    public static void pustMesssge(String jsonMasge) throws MqttException {
        MqttMessage message = new MqttMessage(jsonMasge.getBytes());
        message.setQos(qos);
        mqttClient.publish(pubTopic, message);

    }


    @Override
    public void afterPropertiesSet() throws Exception {
        init();
    }
}

